<?php
namespace Home\Controller;
use Think\Controller;
class OrdersController extends AdminAuthController {
    /**
     * 全部订单
     */
    public function showlists() {
        
        $p_status = I('get.status', '0', 'intval');
        
        $p_ordernum = I('get.ordernum');
        // 筛选条件
        $map = array();
        // 订单号
        if ($p_ordernum) {
            $map['ordernum'] = array('like', "%{$p_ordernum}%");
        } else {
            $map['ordernum'] = array('like', "%%");
        }
        
        // 状态
        if ($p_status) {
            $map['orderstatus'] = array('eq', $p_status);
        } else {
            $map['orderstatus'] = array('gt', '1');
        }
        
        // 未删除
        $map['deled'] = array('eq', '0');
        
        $M_orders = M('orders');
        
        $count = $M_orders->where($map)->count();
        $Page = new \Think\Page($count, 10);
        //定制分页类
        $Page->setConfig('header','<span class="sabrosus">共 %TOTAL_ROW% 条记录</span>'); //显示内容
        $Page->setConfig('prev','上一页');
        $Page->setConfig('next','下一页');
        $Page->setConfig('first','首页');
        $Page->setConfig('last','末页');
        $Page->setConfig('theme'," %HEADER% %FIRST% %UP_PAGE%  %LINK_PAGE% %DOWN_PAGE% %END%");
        $show = $Page -> show();
        
        $orders_list = $M_orders->where($map)->limit($Page->firstRow.','.$Page->listRows)->order('time_end DESC')->select();
        
        $M_orders_buy = M('orders_buy');
        $M_orders_detail = M('orders_detail');
        $M_user = M('user');
        $M_shipper = M('shipper');
        
        foreach ($orders_list as $orders_k=>$orders_v) {
            $orders_list[$orders_k]['user'] = $M_user->field('id,phone,nickname')->find($orders_v['userid']);
            
            $orders_list[$orders_k]['shippername'] = $M_shipper->where('id=' . $orders_v['shipperid'])->getField('name');
            
            $orders_list[$orders_k]['stat'] = $this->trStatus($orders_v['orderstatus'], $orders_v['commented']);
            $orders_list[$orders_k]['detail'] = $M_orders_detail->where('ordernum=' . $orders_v['ordernum'])->find();
            
            $orders_list[$orders_k]['buy'] = $M_orders_buy->where('ordernum=' . $orders_v['ordernum'])->select();
        }
        
        $this->orders_list = $orders_list;
        $this->page = $show;
        
        $this->display();
    }
    
    /**
     * 订单发货 
     */
    public function fahuo($id=0) {
        $M_orders = M('orders');
        $M_user = M('user');
        
        if (IS_POST) {
            $p_id = I('post.id');
            $p_shipperid = I('post.shipperid');
            $p_shippernum = I('post.shippernum');
            
            // 更新状态
            $data = array(
                'orderstatus' => '3',
                'shipperid' => $p_shipperid,
                'shippernum' => $p_shippernum,
                'fhtime' => date('Y-m-d H:i:s'),
            );
            $updated = $M_orders->where(array('id'=>$p_id))->save($data);
            if ($updated) {
                $tmp_order = $M_orders->where(array('id'=>$p_id))->field('ordernum,userid')->find();
                $openid = $M_user->where(array('id'=>$tmp_order['userid']))->getField('openid');
                
                // 发送微信消息提醒
                $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $this->getWxToken();
                
                // 回复图文消息
    			/*$returnXmlArr = array(
    				'touser' => $openid,
    				'msgtype' => 'news',
    				'news' => array(
    					'articles' => array(
    						'title' => '您有1笔订单已发货',
    						'description' => '点击查看详情',
    						'picurl' => '',
    						'url' => WX_URL . U('Index/express', array('id'=>$p_id)),
    					),
    				)
    			);*/
    			
    			$json_msg = '{"touser":"'.$openid.'","msgtype":"news","news":{"articles": [{"title":"您有一笔订单已发货","description":"您的订单编号为：'.$tmp_order['ordernum'].'的订单已发货。","url":"'.WX_URL.'/index.php/Orders/wuliu/id/'.$p_id.'.html","picurl":""}]}}';
    			
    			$this->curlGet($url, null, true, $json_msg);
    			
                $this->success("发货成功！", U("showlists", array('status'=>'2')));
            } else {
                $this->error("发货失败！");
            }
        } else {
            if (!$id) $this->error('参数有误！', U('showlists'));
            
            $id = I("get.id");
            
            $p_status = I('get.status', '0', 'intval');
            
            $M_orders_buy = M('orders_buy');
            $M_orders_detail = M('orders_detail');
            $M_user = M('user');
            
            // 订单信息
            $order_row = $M_orders->find($id);
            
            $order_row['detail'] = $M_orders_detail->where('ordernum=' . $order_row['ordernum'])->find();
            $order_row['buy'] = $M_orders_buy->where('ordernum=' . $order_row['ordernum'])->select();
            
            // 物流信息
            $M_shipper = M('shipper');
            $shipper_rows = $M_shipper->order('showorder DESC')->select();
            
            $this->order_row = $order_row;
            
            $this->shipper_rows = $shipper_rows;
            
            $this->display();
        }
    }
    
    /**
     * 删除订单
     */
    public function del() {
        $M_orders = M('orders');
        
        $id = I("get.id");
        
        $p_status = I('get.status', '0', 'intval');
        
        $del_row = $M_orders->where(array('id'=>$id))->save(array('deled'=>'1'));
        if ($del_row) {
            $this->success("删除成功", U("showlists", array('status'=>$p_status)));
        } else {
            $this->error("删除失败");
        }
    }
    
    /**
     * 订单导出
     */
    public function export() {
        if (IS_POST) {
            $p_status = I('post.status');
            $p_starttime = I('post.starttime');
            $p_endtime = I('post.endtime');
            
            
            if ($p_starttime) {
                $p_starttime = date('Ymd000000', strtotime($p_starttime));
            
                if ($p_endtime) {
                    $p_endtime = date('Ymd000000', strtotime($p_endtime));
                    $map['time_end'] = array('between', array($p_starttime, $p_endtime));
                } else {
                    $map['time_end'] = array('egt', $p_starttime);
                }
            } else {
                if ($p_endtime) {
                    $map['time_end'] = array('elt', date('Ymd000000', strtotime($p_starttime)));
                }
            }
            
            
            if ($p_status) {
                $map['orderstatus'] = array('eq', $p_status);
            } else {
                $map['orderstatus'] = array('egt', '2');
            }
            
            
            ini_set('display_errors', TRUE);
            ini_set('display_startup_errors', TRUE);
            
            require_once LIB_PATH. 'Org/Util/PHPExcel.class.php';
            
            $objPHPExcel = new \PHPExcel();
            
            $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
            ->setLastModifiedBy("Maarten Balliauw")
            ->setTitle("PHPExcel Test Document")
            ->setSubject("PHPExcel Test Document")
            ->setDescription("Test document for PHPExcel, generated using PHP classes.")
            ->setKeywords("office PHPExcel php")
            ->setCategory("Test result file");
            
            // 设置标题
            $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '订单编号')
            ->setCellValue('B1', '会员姓名')
            ->setCellValue('C1', '会员手机号')
            ->setCellValue('D1', '商品信息')
            ->setCellValue('E1', '订单金额')
            ->setCellValue('F1', '下单时间')
            ->setCellValue('G1', '状态')
            ->setCellValue('H1', '支付方式')
            ->setCellValue('I1', '支付金额')
            ->setCellValue('J1', '支付编号')
            ->setCellValue('K1', '支付时间')
            ->setCellValue('L1', '发票信息')
            ->setCellValue('M1', '收货人')
            ->setCellValue('N1', '收货电话')
            ->setCellValue('O1', '收货地址');
            
            
            // 筛选用户信息
            $M_orders = M('orders');
            $M_orders_buy = M('orders_buy');
            $order_rows = $M_orders->join("__USER__ ON __USER__.id=__ORDERS__.userid")->join("__ORDERS_DETAIL__ ON __ORDERS_DETAIL__.ordernum=__ORDERS__.ordernum")->where($map)->order('time_end DESC')->field('ms_orders.*,ms_user.phone,ms_user.nickname,ms_orders_detail.uname,ms_orders_detail.uphone,ms_orders_detail.uaddr')->select();
            
            //var_dump($order_rows);exit;
            
            $i = 1;
            $status_arr = array('', '', '待发货', '待收货', '已完成');
            $paytype_arr = array('积分兑换', '微信');
            
            foreach ($order_rows as $order_k=>$order_v) {
                $i++;
                
                // 商品
                $buy_rows = $M_orders_buy->where(array('ordernum'=>$order_v['ordernum']))->select();
                
                $temp_buys = "";
                foreach ($buy_rows as $k=>$v) {
                    $temp_buys .= $v['title'].' 【数量：'.$v['num'].'】';
                    if ($k) $temp_buys .= "\n";
                }
            
                $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValueExplicit('A'.$i, $order_v['ordernum'], \PHPExcel_Cell_DataType::TYPE_STRING)
                ->setCellValue('B'.$i, $order_v['nickname'])
                ->setCellValueExplicit('C'.$i, $order_v['phone'], \PHPExcel_Cell_DataType::TYPE_STRING)
                ->setCellValue('D'.$i, $temp_buys)
                ->setCellValue('E'.$i, $order_v['money'])
                ->setCellValue('F'.$i, $order_v['addtime'])
                ->setCellValue('G'.$i, $status_arr[$order_v['orderstatus']])
                ->setCellValue('H'.$i, $paytype_arr[$order_v['paytype']])
                ->setCellValue('I'.$i, bcdiv($order_v['total_fee'], 100, 2))
                ->setCellValueExplicit('J'.$i, $order_v['transaction_id'], \PHPExcel_Cell_DataType::TYPE_STRING)
                ->setCellValueExplicit('K'.$i, $order_v['time_end'], \PHPExcel_Cell_DataType::TYPE_STRING)
                ->setCellValue('L'.$i, $order_v['invoice'])
                ->setCellValue('M'.$i, $order_v['uname'])
                ->setCellValueExplicit('N'.$i, $order_v['uphone'], \PHPExcel_Cell_DataType::TYPE_STRING)
                ->setCellValue('O'.$i, $order_v['uaddr']);
            }
            
            //$objPHPExcel->getActiveSheet()->setCellValue('A8',"Hello\nWorld");
            //$objPHPExcel->getActiveSheet()->getRowDimension(8)->setRowHeight(-1);
            //$objPHPExcel->getActiveSheet()->getStyle('A8')->getAlignment()->setWrapText(true);
            
            // Rename worksheet
            $objPHPExcel->getActiveSheet()->setTitle('订单信息导出');
            
            
            // Set active sheet index to the first sheet, so Excel opens this as the first sheet
            $objPHPExcel->setActiveSheetIndex(0);
            
            /*$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
             $objWriter->save(str_replace('.php', '.xlsx', __FILE__));*/
            
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="订单导出'.date('Y-m-d_').rand(1000, 9999).'.xlsx"');
            header('Cache-Control: max-age=0');
            
            $objWriter = \PHPExcel_IOFactory:: createWriter($objPHPExcel, 'Excel2007');
            $objWriter->save( 'php://output');
            
        } else {
            $this->display();
        }
    }
    
    /**
     * 订单状态文本转换
     */
    private function trStatus($stat=0, $commented=0) {
        if (!$stat) return '';
        
        if ($stat == 1) {
            return '待支付';
        } else if ($stat == 2) {
            return '待发货';
        } else if ($stat == 3) {
            return '待收货';
        }  else if ($stat == 4) {
            if ($commented) {
                return '已完成';
            }
            return '待评价';
        }
    }
    
    /**
     * 物流转换
     */
    private function trShipper($shipperid) {
        $M_shipper = M('shipper');
    }
    
    /**
     * 获取access_token
     */
    private function getWxToken() {
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . WX_APPID;
        $url .= '&secret=' . WX_APPSECRET;
    
        $return_data = $this->curlGet($url);
        
        if (!$return_data) return false;
    
        $json_obj = json_decode($return_data);
    
        if ($json_obj->access_token) return $json_obj->access_token;
    
        return false;
    }
    
    /**
     * curl http
     */
    private function curlGet($url, $header=null, $ispost=false, $postdata=null) {
        if(!$url) return -1;
    
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 500);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    
        if($header && is_array($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
    
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0');
    
        if ($ispost AND $postdata) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        } else {
            curl_setopt($ch, CURLOPT_POST, false);
        }
        //curl_setopt($ch, CURLOPT_REFERER, 'http://mobile.umeng.com');
        //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    
        $output = curl_exec($ch);
    
        curl_close($ch);
    
        return $output;
    }
}